<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入标题" :maxlength="255" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="配置项" required prop="ciName">
            <el-input v-model="formItem.ciName" placeholder="请选择配置项" @focus="handleSelectInstances" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="配置项" required prop="ciName">
            <el-input v-model="formItem.ciName" placeholder="请选择配置项" @focus="handleSelectInstances" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="变更来源" prop="source">
            <el-select v-model="formItem.source" class="select_input" placeholder="变更来源" disabled>
              <el-option v-for="(item) in sources" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="申请人" prop="applicant">
            <el-input v-model="formItem.applicant" placeholder="请输入申请人" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请方式" prop="contactInformation">
            <el-input
              v-model="formItem.contactInformation"
              placeholder="请输入联系信息"
            >
              <el-select slot="prepend" v-model="formItem.applicationType" style="width: 100px;" placeholder="请选择" @change="changeType">
                <el-option v-for="item in applicationTypes" :key="item.code" :label="item.text" :value="item.code" />
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请时间" prop="applicationTime">
            <el-date-picker
              v-model="formItem.applicationTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="影响范围" prop="influenceCoverage">
            <el-select v-model="formItem.influenceCoverage" class="select_input" placeholder="影响范围" @change="selectChange">
              <el-option v-for="(item) in influenceCoverages" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgencyDegree">
            <el-select v-model="formItem.urgencyDegree" class="select_input" placeholder="紧急程度" @change="selectChange">
              <el-option v-for="(item) in urgencyDegrees" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="formItem.priority" class="select_input" placeholder="优先级">
              <el-option v-for="(item) in prioritys" :key="item.priority" :label="item.priorityName" :value="item.priority" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="执行人" prop="executor">
            <el-input v-model="formItem.executor" placeholder="请选择执行人" @focus="handleUserIconClick" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachments"
              :before-upload="handleBeforeUpLoad"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="详细说明" prop="description">
            <!-- <Tinymce ref="tinymce" v-model="formItem.description" :height="200" menubar="false" /> -->
            <el-input v-model="formItem.description" placeholder="请输入内容" :rows="10" :maxlength="2047" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <div style="text-align: right;">
        <el-form-item>
          <el-button type="warning" @click="ok('temporary')">暂存</el-button>
          <el-button type="primary" @click="ok('submit')">提交</el-button>
        </el-form-item>
      </div>
    </el-form>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择执行人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.orgCode" />
    </SelectDialog>
    <!-- <SelectDialog v-if="instanceSelDialogFormVisible" title="选择维护对象" width="90%" :append-to-body="true" :show="instanceSelDialogFormVisible" @on-ok="selectInstanceOk" @on-cancel="selectInstanceCancel">
      <instancesTable ref="instancesTable" :for-selection="true" />
    </SelectDialog> -->
    <SelectDialog v-if="instanceSelDialogFormVisible" title="选择维护对象" width="90%" :append-to-body="true" :show="instanceSelDialogFormVisible" @on-ok="selectInstanceOk" @on-cancel="selectInstanceCancel">
      <instancesTable ref="instancesTable" :for-selection="true" />
    </SelectDialog>
  </div>
</template>

<script>
import {
  create,
  detail,
  importUrl,
  deleteAttachmentByFsId
} from '@neu/dcom-ui/api/changeRegistration'
import { getByParams } from '@neu/dcom-ui/api/priority'
// import Tinymce from '@neu/biz-core/components/Tinymce'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import UsersPage from '@neu/auth-ui/views/users/tables'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
// import instancesTable from '@neu/dcom-ui/views/instancesFromModel/tables'
import instancesTable from '@neu/dcam-ui/views/fixedAsset'
import { getToken } from '@neu/biz-core/utils/auth'

const formItem = {
  title: '',
  ciId: '',
  ciCode: null,
  ciName: '',
  applicationType: '',
  contactInformation: '',
  applicationTime: '',
  influenceCoverage: '',
  urgencyDegree: '',
  priority: '',
  source: 'USER_REPORT_CHANGE',
  description: '',
  executorCode: '',
  executor: '',
  status: '',
  // 附件列表
  attachments: [],
  workOrderNum: '',
  taskId: ''
}
export default {
  name: 'ChangeRegistration',
  components: {
    // Tinymce,
    UsersPage,
    SelectDialog,
    instancesTable
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      /** 上传路径 */
      importUrl: importUrl,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      /** 配置项dialog */
      instanceSelDialogFormVisible: false,
      /** 优先级 */
      prioritys: [],
      /** 事件来源 */
      sources: [],
      /** 申请方式 */
      applicationTypes: [],
      /** 影响范围 */
      influenceCoverages: [],
      /** 紧急程度 */
      urgencyDegrees: [],
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        title: [{
          required: true,
          message: '标题不能为空',
          trigger: 'blur'
        }],
        applicant: [{
          required: true,
          message: '申请人不能为空',
          trigger: 'blur'
        }],
        ciName: [{
          required: true,
          message: '配置项不能为空',
          trigger: 'change'
        }],
        executor: [{
          required: true,
          message: '执行人不能为空',
          trigger: 'change'
        }],
        applicationType: [{
          required: true,
          message: '申请方式不能为空',
          trigger: 'change'
        }],
        contactInformation: [{
          required: true,
          message: '联系信息不能为空',
          trigger: 'blur'
        }],
        applicationTime: [{
          required: true,
          message: '申请时间不能为空',
          trigger: 'change'
        }],
        influenceCoverage: [{
          required: true,
          message: '影响范围不能为空',
          trigger: 'change'
        }],
        urgencyDegree: [{
          required: true,
          message: '紧急程度不能为空',
          trigger: 'change'
        }],
        priority: [{
          required: true,
          message: '优先级不能为空',
          trigger: 'change'
        }],
        source: [{
          required: true,
          message: '变更来源不能为空',
          trigger: 'change'
        }],
        description: [{
          required: true,
          message: '详细说明不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  watch: {},
  created() {
    findByDictionaryType('coverageInfluence').then(response => {
      this.influenceCoverages = response.data
    })
    findByDictionaryType('urgency').then(response => {
      this.urgencyDegrees = response.data
    })
    findByDictionaryType('applyType').then(response => {
      this.applicationTypes = response.data
    })
    findByDictionaryType('ChangeSource').then(response => {
      this.sources = response.data
    })
    this.fetch()
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
          getByParams(this.formItem.influenceCoverage, this.formItem.urgencyDegree).then(response => {
            this.prioritys = response.data
          })
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    ok(value) {
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            this.formItem.status = value
            create(this.formItem).then(res => {
              if (res.status === 'success') {
                this.$emit('cancelNewOrderForm', 'refresh')
              }
            })
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      this.formItem = { ...formItem }
    },
    selModel(node) {
      this.formItem.objName = node.name
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      this.userSelDialogFormVisible = true
    },
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个执行人',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.executorCode = ''
        this.formItem.executor = ''
      } else {
        this.formItem.executorCode = users[0].username
        this.formItem.executor = users[0].name ? users[0].name : users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    changeType(value) {},
    selectInstanceOk() {
      // const instances = this.$refs.instancesTable.$refs.myTable.selectionRows
      const instances = this.$refs.instancesTable.selections
      if (instances.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个配置项',
          type: 'error'
        })
      }
      if (instances.length < 1) {
        this.formItem.ciId = ''
        this.formItem.ciCode = ''
        this.formItem.ciName = ''
      } else {
        this.formItem.ciId = instances[0].id
        this.formItem.ciCode = instances[0].code
        this.formItem.ciName = instances[0].name
      }
      this.instanceSelDialogFormVisible = false
    },
    selectInstanceCancel() {
      this.instanceSelDialogFormVisible = false
    },
    /** 选择对象 */
    handleSelectInstances() {
      this.instanceSelDialogFormVisible = true
    },
    selectChange() {
      if (this.formItem.influenceCoverage !== '' && this.formItem.urgencyDegree !== '') {
        getByParams(this.formItem.influenceCoverage, this.formItem.urgencyDegree).then(response => {
          this.prioritys = response.data
        })
      }
    },
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachments.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachments.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    handleError(err, file, fileList) {
      console.log(err)
    },
    handleRemove(file, fileList) {
      deleteAttachmentByFsId(file.fsId, this.id).then(res => {
        if (res.status === 'failure') {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'error'
          })
        } else {
          this.formItem.attachments.splice(this.formItem.attachments.indexOf(file), 1)
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }
      })
    },
    handleBeforeUpLoad(file) {

    }
  }
}
</script>
